package com.ilink.ilinkuser.service.impl;

/**
 * <h3>new-ilink-java-backend-psy</h3>
 *
 * @Description <p>实现从表到用户信息的同步导入</p>
 * @Author pengshiyao
 * @Date 2024-10-09 11:39
 **/

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.ilink.ilinkcommon.domain.PO.userService.UserMessageExport;
import com.ilink.ilinkcommon.domain.PO.userService.UserProjectParticipation;
import com.ilink.ilinkcommon.domain.User;
import com.ilink.ilinkuser.mapper.UserMapper;
import com.ilink.ilinkuser.mapper.UserMessageExportMapper;
import com.ilink.ilinkuser.mapper.UserProjectParticipationMapper;
import com.ilink.ilinkuser.service.UserMessageExportService;
import com.opencsv.bean.CsvToBean;
import com.opencsv.bean.CsvToBeanBuilder;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

/**
 * @ClassName UserMessageExportServiceImpl
 * @Description
 * @Author pengshiyao
 * @Date 2024-10-09 11:39
 **/
@Service
@Transactional
public class UserMessageExportServiceImpl extends ServiceImpl<UserMessageExportMapper, UserMessageExport>
    implements UserMessageExportService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserProjectParticipationMapper userProjectParticipationMapper;

    //更新对应用户和项目信息
    //原本只有某一项为空字符串或者null时才覆盖，目前已修改为强制覆盖
//    private void updateUser(User user,UserMessageExport userMessageExport) {
//
//        //1.用户存在时，覆盖用户认证信息
//        if (user != null) {
//
//            user.setEmail(userMessageExport.getEmail());
//
//            user.setSchoolName(userMessageExport.getSchool());
//
//            user.setRealname(userMessageExport.getRealname());
//
//            user.setUserGrade(userMessageExport.getEnrollmentYear());
//
//            user.setUserMobile(userMessageExport.getPhoneNumber());
//
//            user.setUserMajor(userMessageExport.getCollege());
//
//            user.setUserCampus(userMessageExport.getCampus());
//
//            user.setUserCollege(userMessageExport.getCollege());
//
//            user.setStudentStatus(userMessageExport.getStudentStatus());
//
//            user.setEnrollmentYear(userMessageExport.getEnrollmentYear());
//
//            userMapper.update(user,new LambdaQueryWrapper<User>().eq(User::getUserId,user.getUserId()));
//
//            //2.写入项目参与情况
//
//            UserProjectParticipation userProjectParticipation = userProjectParticipationMapper.selectOne(new LambdaQueryWrapper<UserProjectParticipation>().eq(UserProjectParticipation::getUserId, user.getUserId()).last("limit 1"));
//            if (userProjectParticipation != null) {
//                userProjectParticipation.setParticipationType(userMessageExport.getParticipationType());
//                userProjectParticipation.setProjectStatus(userMessageExport.getProjectStatus());
//                userProjectParticipation.setProjectType(userMessageExport.getProjectType());
//                userProjectParticipation.setProjectName(userMessageExport.getProjectName());
//                userProjectParticipationMapper.updateById(userProjectParticipation);
//
//            }else {
//                //还没有参与项目的记录
//                userProjectParticipation = new UserProjectParticipation();
//                userProjectParticipation.setUserId(user.getUserId());
//                userProjectParticipation.setProjectName(userMessageExport.getProjectName());
//                userProjectParticipation.setParticipationType(userMessageExport.getParticipationType());
//                userProjectParticipation.setProjectStatus(userMessageExport.getProjectStatus());
//                userProjectParticipation.setProjectType(userMessageExport.getProjectType());
//                userProjectParticipationMapper.insert(userProjectParticipation);
//            }
//
//            //已经强制覆盖过了
//            userMessageExport.setIsSync(1);
//
//
//        }
//
//    }
    private void updateUser(User user,UserMessageExport userMessageExport) {

        //1.用户存在时，覆盖用户认证信息
        if (user != null) {
            int setNum=0;
            if (userMessageExport.getEmail() != null && !userMessageExport.getEmail().isEmpty()) {
                user.setEmail(userMessageExport.getEmail());
                setNum += 1;
            }
            if (userMessageExport.getSchool() != null && !userMessageExport.getSchool().isEmpty()) {
                user.setSchoolName(userMessageExport.getSchool());
                setNum += 1;
            }
            if (userMessageExport.getRealName() != null && !userMessageExport.getRealName().isEmpty()) {
                user.setRealname(userMessageExport.getRealName());
                setNum += 1;
            }
            if (userMessageExport.getEnrollmentYear() != null && !userMessageExport.getEnrollmentYear().isEmpty()) {
                user.setUserGrade(userMessageExport.getEnrollmentYear());
                setNum += 1;
            }
            if (userMessageExport.getPhoneNumber() != null && !userMessageExport.getPhoneNumber().isEmpty()) {
                user.setUserMobile(userMessageExport.getPhoneNumber());
                setNum += 1;
            }
            if (userMessageExport.getCollege() != null && !userMessageExport.getCollege().isEmpty()) {
                user.setUserMajor(userMessageExport.getCollege());
                setNum += 1;
            }
            if (userMessageExport.getCampus() != null && !userMessageExport.getCampus().isEmpty()) {
                user.setUserCampus(userMessageExport.getCampus());
                setNum += 1;
            }
            if (userMessageExport.getCollege() != null && !userMessageExport.getCollege().isEmpty()) {
                user.setUserCollege(userMessageExport.getCollege());
                setNum += 1;
            }
            if (userMessageExport.getStudentStatus() != null && !userMessageExport.getStudentStatus().isEmpty()) {
                user.setStudentStatus(userMessageExport.getStudentStatus());
                setNum += 1;
            }
            if (userMessageExport.getEnrollmentYear() != null && !userMessageExport.getEnrollmentYear().isEmpty()) {
                user.setEnrollmentYear(userMessageExport.getEnrollmentYear());
                setNum += 1;
            }

            //判断只要有一个set了
            if (setNum>0){
                userMapper.update(user,new LambdaQueryWrapper<User>().eq(User::getUserId,user.getUserId()));
            }
            //2.写入项目参与情况
            int setProjectPartNum=0;
            UserProjectParticipation userProjectParticipation = userProjectParticipationMapper.selectOne(new LambdaQueryWrapper<UserProjectParticipation>().eq(UserProjectParticipation::getUserId, user.getUserId()).last("limit 1"));
            if (userProjectParticipation != null) {
                if (userMessageExport.getParticipationType() != null && !userMessageExport.getParticipationType().isEmpty()) {
                    userProjectParticipation.setParticipationType(userMessageExport.getParticipationType());
                    setProjectPartNum += 1;
                }
                if (userMessageExport.getProjectStatus() != null && !userMessageExport.getProjectStatus().isEmpty()) {
                    userProjectParticipation.setProjectStatus(userMessageExport.getProjectStatus());
                    setProjectPartNum += 1;
                }
                if (userMessageExport.getProjectType() != null && !userMessageExport.getProjectType().isEmpty()) {
                    userProjectParticipation.setProjectType(userMessageExport.getProjectType());
                    setProjectPartNum += 1;
                }
                if (userMessageExport.getProjectName() != null && !userMessageExport.getProjectName().isEmpty()) {
                    userProjectParticipation.setProjectName(userMessageExport.getProjectName());
                    setProjectPartNum += 1;
                }

                if (setProjectPartNum>0){
                    userProjectParticipationMapper.updateById(userProjectParticipation);
                }
            }else {
                //还没有参与项目的记录
                userProjectParticipation = new UserProjectParticipation();
                userProjectParticipation.setUserId(user.getUserId());
                userProjectParticipation.setProjectName(userMessageExport.getProjectName());
                userProjectParticipation.setParticipationType(userMessageExport.getParticipationType());
                userProjectParticipation.setProjectStatus(userMessageExport.getProjectStatus());
                userProjectParticipation.setProjectType(userMessageExport.getProjectType());
                userProjectParticipationMapper.insert(userProjectParticipation);
                setProjectPartNum+=1;
            }


            if (setProjectPartNum+setNum>0){
                //已经覆盖过了
                userMessageExport.setIsSync(1);
            }

        }

    }

    @Override
    public boolean importUserMessageTable(MultipartFile csvFile) {
        try (Reader reader = new InputStreamReader(csvFile.getInputStream(
            ))) {//StandardCharsets.UTF_8
            CsvToBean<UserMessageExport> csvToBean = new CsvToBeanBuilder<UserMessageExport>(reader)
                .withType(UserMessageExport.class)
                .withIgnoreLeadingWhiteSpace(true)
                .build();
            List<UserMessageExport> UserMessageExports = csvToBean.parse();

            //  对于已经存在的数据进行不覆盖，直接跳过.否则进行覆盖或者写入
            UserMessageExports.forEach(userMessageExport -> {
                LambdaQueryWrapper<UserMessageExport> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(UserMessageExport::getCampus, userMessageExport.getCampus())
                    .eq(UserMessageExport::getEmail, userMessageExport.getEmail())
                    .eq(UserMessageExport::getEnrollmentYear, userMessageExport.getEnrollmentYear())
                    .eq(UserMessageExport::getPhoneNumber, userMessageExport.getPhoneNumber())
                    .eq(UserMessageExport::getProjectName, userMessageExport.getProjectName())
                    .eq(UserMessageExport::getProjectStatus, userMessageExport.getProjectStatus())
                    .eq(UserMessageExport::getProjectType, userMessageExport.getProjectType())
                    .eq(UserMessageExport::getRealName, userMessageExport.getRealName())
                    .eq(UserMessageExport::getSchool, userMessageExport.getSchool())
                    .eq(UserMessageExport::getStudentId, userMessageExport.getStudentId())
                    .eq(UserMessageExport::getStudentStatus, userMessageExport.getStudentStatus())
                    .eq(UserMessageExport::getParticipationType, userMessageExport.getParticipationType())
                    .eq(UserMessageExport::getCollege, userMessageExport.getCollege());

                if (this.count(queryWrapper) == 0) {
                    //当写入数据有更新，先统一更新到对应用户
                    //存入前进行先对有学号的进行覆盖,严格依照学号和名字匹配
                    User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getSchoolId, userMessageExport.getStudentId()).eq(User::getRealname,userMessageExport.getRealName()).last("limit 1"));
                    updateUser(user,userMessageExport);
                    this.save(userMessageExport);
                }
            });
            return true;

        }catch (Exception e) {
            log.error("导入用户统计信息错误", e);
            throw new RuntimeException("导入用户统计信息错误");
//            return false;
        }

    }

    @Override
    public boolean syncUserMessage(User user) {
        //按照学号和名字找可用覆盖信息
        UserMessageExport userMessageExport = this.baseMapper.selectOne(new LambdaQueryWrapper< UserMessageExport>()
            .eq( UserMessageExport::getStudentId, user.getSchoolId()).eq(UserMessageExport::getRealName,user.getRealname()).last("limit 1"));
        if (userMessageExport != null) {
            if (userMessageExport.getIsSync() == 1) {
                return true;
            }
            //如果没覆盖更新过，进行覆盖更新
            updateUser(user,userMessageExport);
            if (userMessageExport.getIsSync() == 0) {
                return false;
            }else {
                //更新覆盖状态到数据库
                this.updateById(userMessageExport);
                return true;
            }

        }

        return false;
    }
}
